<!DOCTYPE>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
	<script src="js/jquery.js"></script>
	<script>
		$(() => {
			/*No cache for css*/
			$('link.cssLink').each((index, element) => {
				let url = $(element).attr('href');
				url += '?rand=' + Math.random();
				$(element).attr('href', url);
			});
			
			/*Auto completion function*/
			$('#searchInput').on('keydown', (e) => {
				let keyword = $(e.target).val();
				let requestData = 'keyword=' + keyword;
				console.log(requestData);
				$.ajax({
					url: 'Search',
					method: 'GET',
					accept: 'application/json',
					data: requestData,
					success: (productList, status) => {
						let dataList = $('#autoCompletion');
						/*Clear the origin datalist*/
						dataList.children().remove();
						productList.forEach((element, index) => {
							/*Max number of auto completion is 10
                            Although this should be done in server*/
							const MAX_NUMBER_OF_COMPLETION = 10;
							if (index < MAX_NUMBER_OF_COMPLETION) {
								dataList.append('<option class="autocomplete-option" value="' + element.name + '">' + element.name + '</option>');
							}
						});
						
					}
				});
			});
			
		});
	</script>
	<link class="cssLink" href="css/jpetstore.css" media="screen"
		  rel="StyleSheet" type="text/css"/>
	<link href="css/icono.min.css" rel="stylesheet" type="text/css">
	<link class="cssLink" href="css/mycss.css" rel="stylesheet" type="text/css">
	<meta content="HTML Tidy for Linux/x86 (vers 1st November 2002), see www.w3.org"
		  name="generator"/>
	<title>MyPetStore</title>
	<meta charset="UTF-8">
	<meta content="text/html; charset=UTF-8"
		  http-equiv="Content-Type"/>
	<meta content="max-age=0" http-equiv="Cache-Control"/>
	<meta content="no-cache" http-equiv="Cache-Control"/>
	<meta content="0" http-equiv="expires"/>
	<meta content="Tue, 01 Jan 1980 1:00:00 GMT" http-equiv="Expires"/>
	<meta content="no-cache" http-equiv="Pragma"/>
</head>
<body>
<div th:include="common/top.html::top"></div>
<div id="content">
	<div id="BackLink">
		<a href="Main">Return to Main Menu</a>
	</div>
	<script>
		$(() => {
			'use strict';
			$('button').each((i, val) => {
				$(val).on('click', (e) => {
					e.preventDefault();
					let itemID = $(e.target).parent().parent().attr('id');
					$.get('RemoveItem?itemId=' + itemID, (data) => {
						if (data === 'true') {
							$('#' + itemID).remove();
							checkEmpty();
							calculateValue();
						}
					});
				});
			});
			$('input.qty').each((i, val) => {
				$(val).on('blur', (e) => {
					let itemId = $(e.target).parent().parent().attr('id');
					let qty = $(e.target).val();
					
					$.ajax({
						url: 'Update',
						method: 'GET',
						data: 'id=' + itemId + '&newQuantity=' + qty,
						success: (data, status) => {
							if (data !== 'true') {
								alert('Update Failed');
							}
							else {
								calculateValue();
								checkEmpty();
							}
						}
					});
				});
			});
			let checkEmpty = () => {
				if ($('tr').length < 4) {
					$('#tableHead').after('<tr id=\'emptyInfo\'><td colspan="8"><b>Your cart is empty.</b></td></tr>');
					$('#subTotal').val(0);
				}
				else
					$('#emptyInfo').remove();
			};
			
			let calculateValue = () => {
				let value = 0;
				$('tr.itemLine').each((index, element) => {
					let quantity = parseInt($(element).children('td.quantityTd').children('input.qty').val());
					let pattern = new RegExp('\\d+\\.\\d{2}');
					let listPrice = pattern.exec($(element).children('td.listPrice').text());
					listPrice = parseFloat(listPrice.toString());
					$(element).children('td.lineTotal').text('$' + quantity * listPrice);
					value += quantity * listPrice;
				});
				$('#subTotal').text('Sub Total: $' + value);
			};
			
			$('#check-out').on('click', (e) => {
				e.preventDefault();
				$('#info-form').css('display', 'block');
			});
			
			$('#close-order-info').on('click', (e) => {
				e.preventDefault();
				$('#info-form').css('display', 'none');
			});
			
			$('#ship-address-required').on('change', (e) => {
				if ($(e.target).is(':checked')) {
					$('#ship-address-table').css('display', 'table');
				}
				else {
					$('#ship-address-table').css('display', 'none');
				}
			});
			
			let generateDefaultShipAddress = () => {
				$('input[name="shipFirstName"]').val($('input[name="billFirstName"]').val());
				$('input[name="shipLastName"]').val($('input[name="billLastName"]').val());
				$('input[name="shipAddress"]').val($('input[name="billAddress"]').val());
				$('input[name="shipCity"]').val($('input[name="billCity"]').val());
				$('input[name="shipState"]').val($('input[name="billState"]').val());
				$('input[name="shipZip"]').val($('input[name="billZip"]').val());
				$('input[name="shipCountry"]').val($('input[name="billCountry"]').val());
			};
			
			$('#info-form').on('submit', (e) => {
				e.preventDefault();
				if (!$('#ship-address-required').is(':checked')) {
					generateDefaultShipAddress();
				}
				let data = {};
				let fields = $('#info-form').serializeArray();
				$.each(fields, (index, value) => data[value['name']] = value['value']);
				console.log(data);
				data = JSON.stringify(data);
				console.log(data);
				$.ajax({
					url: 'MakeOrder',
					method: 'POST',
					data: data,
					dataType: 'JSON',
					contentType: 'application/json',
					success: (data, status) => {
						if (data['error'] !== undefined) {
							alert(data['error']);
							window.location.reload();
						}
						else {
							window.location = 'OrderDetail?orderID=' + data['orderId'];
						}
					},
					error: (xhr, msg) => {
						alert(xhr.status);
						alert(msg);
					}
				});
				
			});
			
		});
	</script>
	<div id="Catalog">
		<div id="order-info">
			<form id="info-form" method="post">
				<h2>Confirm Your Order</h2>
				<table id="bill-address-table">
					<tbody>
					<tr>
						<th colspan="2">Payment Details</th>
					</tr>
					<tr>
						<td>Card Type:</td>
						<td><select name="cardType">
							<option selected="selected" value="Visa">Visa</option>
							<option value="MasterCard">MasterCard</option>
							<option value="American Express">American Express</option>
						</select></td>
					</tr>
					<tr>
						<td>Card Number:</td>
						<td><input name="creditCard" type="text" value="999 9999 9999 9999"> * Use a fake
							number!
						</td>
					</tr>
					<tr>
						<td>Expiry Date (MM/YYYY):</td>
						<td><input name="expiryDate" type="text" value="12/03"></td>
					</tr>
					<tr>
						<th colspan="2">Billing Address</th>
					</tr>
					
					<tr>
						<td>First name:</td>
						<td><input name="billToFirstName" th:value="${session.loginUser.firstName}" type="text"
								   value="firstName"></td>
					</tr>
					<tr>
						<td>Last name:</td>
						<td><input name="billToLastName" th:value="${session.loginUser.lastName}" type="text"
								   value="lastName"></td>
					</tr>
					<tr>
						<td>Address 1:</td>
						<td><input name="billAddress" size="40" th:value="${session.loginUser.address1}" type="text"
								   value="address">
						</td>
					</tr>
					<tr>
						<td>City:</td>
						<td><input name="billCity" th:value="${session.loginUser.city}" type="text" value="city"></td>
					</tr>
					<tr>
						<td>State:</td>
						<td><input name="billState" size="4" th:value="${session.loginUser.state}" type="text"
								   value="state"></td>
					</tr>
					<tr>
						<td>Zip:</td>
						<td><input name="billZip" size="10" th:value="${session.loginUser.zip}" type="text" value="zip">
						</td>
					</tr>
					<tr>
						<td>Country:</td>
						<td><input name="billCountry" size="15" th:value="${session.loginUser.country}" type="text"
								   value="country">
						</td>
					</tr>
					
					<tr>
						<td colspan="2">
							<input id="ship-address-required" type="checkbox">
							Ship to different address...
						</td>
					</tr>
					</tbody>
				</table>
				
				<table id="ship-address-table">
					<tr>
						<th colspan=2>Shipping Address</th>
					</tr>
					
					<tr>
						<td>First name:</td>
						<td><input name="shipToFirstName" th:value="${session.loginUser.firstName}" value="firstName">
						</td>
					</tr>
					<tr>
						<td>Last name:</td>
						<td><input name="shipToLastName" th:value="${session.loginUser.lastName}" value="lastName"></td>
					</tr>
					<tr>
						<td>Address 1:</td>
						<td><input name="shipAddress" th:value="${session.loginUser.address1}" value="address1"></td>
					</tr>
					<tr>
						<td>City:</td>
						<td><input name="shipCity" th:value="${session.loginUser.city}" value="city"></td>
					</tr>
					<tr>
						<td>State:</td>
						<td><input name="shipState" th:value="${session.loginUser.state}" value="state"></td>
					</tr>
					<tr>
						<td>Zip:</td>
						<td><input name="shipZip" th:value="${session.loginUser.zip}" value="zip"></td>
					</tr>
					<tr>
						<td>Country:</td>
						<td><input name="shipCountry" th:value="${session.loginUser.country}" value="country"></td>
					</tr>
				</table>
				
				<input name="newOrder" type="submit" value="Confirm">
				<input id="close-order-info" type="button" value="Close">
			</form>
		</div>
		<div id="Cart">
			
			<h2>Shopping Cart</h2>
			<form action="Cart?method=update" method="post">
				<table>
					<tr id="tableHead">
						<th><b>Item ID</b></th>
						<th><b>Product ID</b></th>
						<th><b>Description</b></th>
						<th><b>In Stock?</b></th>
						<th><b>Quantity</b></th>
						<th><b>List Price</b></th>
						<th><b>Total Cost</b></th>
						<th><b> </b></th>
					</tr>
					<tr th:if="${session.loginUser.cart == null}">
						<td colspan="8"><b>Your cart is empty.</b></td>
					</tr>
					<!-- 循环 -->
					<tr class="itemLine" id="123"
						th:each="temp : ${session.loginUser.cart.itemCartItemMap.values()}" th:id="${temp.item.itemId}">
						<td><a href="Item?itemID=123" th:href="'Item?itemID='+${temp.item.itemId}"
							   th:text="${temp.item.itemId}">123</a></td>
						<td th:text="${temp.item.product.productId}">productID</td>
						<td th:utext="${temp.item.product.description}">description</td>
						<td th:text="${temp.item.quantity ge 0 }">true</td>
						<td class="quantityTd"><input class="qty" id="qtyid"
													  name="itemIdnewQuantity" th:id="'qty'+${temp.item.itemId}"
													  th:name="${temp.item.itemId} + 'newQuantity'"
													  th:value="${temp.quantity}"
													  type="number"
													  value="quantity"></td>
						<td class="listPrice">
							<span th:text="'$'+${temp.item.listPrice}">$114514.1919810</span>
						</td>
						<td class="lineTotal">
							<span th:text="'$'+${temp.total}">$114514.1919810</span>
						</td>
						<td>
							<button class="removeItem" id="buttonitemId" th:id="'button+'+${temp.item.itemId}">
								Remove
							</button>
						</td>
					</tr>
					<tr>
						<td colspan="8" id="subTotal">Sub Total: <!-- 判断 -->
							<span th:text="'$'+${session.loginUser.cart.total}">$1145141919810</span>
						</td>
					</tr>
					<tr>
						<td><input class="Button" disabled="disabled" type="submit" value="Update Cart"/></td>
					</tr>
				</table>
			</form>
			
			<!-- 需要判断是否登录 -->
			
			<a class="Button" href="NewOrder" id="check-out">Proceed to Checkout</a>
		</div>
		
		<div id="MyList">
			<!-- 判断 -->
			<!--<include file="IncludeMyList.html"/>-->
		</div>
		
		<div id="Separator">&nbsp;</div>
	</div>
</div>
<div th:include="common/bottom.html::bottom"></div>
</body>
</html>
	